<?php

/**
 * [PHPFOX_HEADER]
 */
defined('PHPFOX') or exit('NO DICE!');

/**
 * 
 * 
 * @copyright		[PHPFOX_COPYRIGHT]
 * @author  		Raymond Benc
 * @package 		Phpfox_Ajax
 * @version 		$Id: ajax.class.php 892 2009-08-24 13:23:36Z Raymond_Benc $
 */
class Takepicture_Component_Ajax_Ajax extends Phpfox_Ajax {

    public function uploadToSocial() {

        
        if (($aVals = $this->get('val'))) {
            if ($aVals['type'] == "pixel") {
                // input is in format 1,2,3...|1,2,3...|...
                $im = imagecreatetruecolor(320, 240);

                foreach (explode("|", $aVals['image']) as $y => $csv) {
                    foreach (explode(";", $csv) as $x => $color) {
                        imagesetpixel($im, $x, $y, $color);
                    }
                }
            } else {
                // input is in format: data:image/png;base64,...
                $im = imagecreatefrompng($aVals['image']);
            }
            
            $sFileName = uniqid() . date('YmdHis') . '.png';
            $sDirImage = Phpfox::getParam('takepicture.dir_pic') . $sFileName;
            $sUrlImage = Phpfox::getParam('takepicture.url_pic') . $sFileName;
            
            if(!imagepng($im, $sDirImage)) {
                Phpfox_Error::set('Can not save Image');
            }
            
            $aListSocial = isset($aVals['social']) ? $aVals['social'] : array();
            $sMessage = $aVals['message'];

            $aRows = Phpfox::getService('takepicture')->getListSocial($aListSocial);

            if ($aRows) :

                foreach ($aRows as $item) :
                    //restore session
                    Phpfox::getService('loginsocial.process')->initHandle(array(
                        'session_data' => $item['session_data'],
                        'provider' => $item['provider']
                    ));

                    //check connect with current social
                    if (Phpfox::getService('loginsocial.process')->getHybridAuth()->isConnectedWith($item['provider'])) {
                        //post photo
                        $aReponse = Phpfox::getService('loginsocial.process')->getAdapter()->postPhoto(array(
                            'dir' => $sDirImage,
                            'url' => $sUrlImage,
                            'message' => $aVals['message'],
                        ));
                    }
                endforeach;

            endif;
            @unlink($sDirImage);
            
            $this->setMessage('Photo uploaded succesfully');
        } else {
            Phpfox::getComponent('takepicture.upload-to-social');
        }
    }

}

?>